package com.xyht.sca_s.student_manage_system.modules.common.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.MultipartFileToFileUtils;
import com.xyht.sca_s.student_manage_system.modules.common.constant.FileSavePathConstant;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.common.service.SmsFileUpDownService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

import static com.xyht.sca_s.student_manage_system.modules.common.constant.FileSavePathConstant.*;
import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;

/**
 * <p>
 * 批量导入任务表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2022-11-29
 */
@Service
public class SmsFileUpDownServiceImpl extends ServiceImpl<SmsImportTaskMapper, SmsImportTask> implements SmsFileUpDownService {

    @Resource
    private FileSavePathConstant fileSavePathConstant;
    @Override
    public ResponseResult fileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String fileName = file.getOriginalFilename();

        int size = Math.round(file.getSize() / 1024);
        int sizeMB = Math.round(size / 1024);
        if (sizeMB > fileSavePathConstant.getIMG_UPLOAD_MAX()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        }
        if (size == fileSavePathConstant.getFILE_UPLOAD_MIN()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_MIN);
        }
        log.debug(fileName + "-->" + size + "KB");
//        String[] fileTypeArr = fileName.split("u002E");
//        String fileType = fileTypeArr[fileTypeArr.length - 1];

        String timeTemp = new Date().getTime() + "";

        String completePath = "";
        String newFileName = "";
        if (fileName.lastIndexOf(".") == -1) {
            completePath = filePath + timeTemp;
            newFileName = timeTemp;
        } else {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            completePath = filePath + timeTemp + "." + suffix;
            newFileName = timeTemp + "." + suffix;
        }

        File dest = new File(completePath);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            Map<String, Object> map = new HashMap<>();
            map.put("oldFileName", fileName);
            map.put("newFileName", newFileName);
            return CommonResult.success(map);
        } catch (MaxUploadSizeExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
    }

    @Override
    public ResponseResult userPicUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String fileName = file.getOriginalFilename();

        int size = Math.round(file.getSize() / 1024);
        int sizeMB = Math.round(size / 1024);
        if (sizeMB > fileSavePathConstant.getUSER_PIC_UPLOAD_MAX()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        }
        if (size == fileSavePathConstant.getFILE_UPLOAD_MIN()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_MIN);
        }
        log.debug(fileName + "-->" + size + "KB");
        String[] fileTypeArr = fileName.split("\\.");
        String fileType = fileTypeArr[fileTypeArr.length - 1];

        String timeTemp = new Date().getTime() + "";
        String completePath = filePath + timeTemp + "." + fileType;
        String newFileName = timeTemp + "." + fileType;
        File dest = new File(completePath);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            Map<String, Object> map = new HashMap<>();
            map.put("oldFileName", fileName);
            map.put("newFileName", newFileName);
            return CommonResult.success(map);
        } catch (MaxUploadSizeExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
    }

    @Override
    public ResponseResult fileDownload(String path, HttpServletResponse response) {
        String fileName = "";
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();
        String completePath = filePath + path;

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                log.debug("fileName=====" + file.getName());
                response.setContentType("application/force-download");
//                response.setContentType("image/**");
                response.setCharacterEncoding("UTF-8");
                // response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
//                response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
    }
    @Override
    public ResponseResult waterMarkDownload(String path, HttpServletResponse response) {
        String fileName = "";
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getWATER_MARK_DOWNLOAD_PATH()
                : fileSavePathConstant.getWATER_MARK_DOWNLOAD_PATH_LINUX();
        String completePath = filePath + path;

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                log.debug("fileName=====" + file.getName());
                response.setContentType("application/force-download");
//                response.setContentType("image/**");
                response.setCharacterEncoding("UTF-8");
                // response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
//                response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
    }

    @Override
    public ResponseResult moduleDownload(String path, HttpServletResponse response) {
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
//        if (!path.equals("student") && !path.equals("teacher")){
//            return  CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
//        }
        String fileName = "";
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_MODULE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_MODULE_DOWNLOAD_PATH_LINUX();
        String completePath = filePath + path + ".xlsx";

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                String moduleName;
                if (path.equals("student")) {
                    moduleName = "学生信息导入模板.xlsx";
                } else if (path.equals("teacher")) {
                    moduleName = "员工信息导入模板.xlsx";
                } else if (path.equals("fixed_asset")) {
                    moduleName = "固定资产导入模板.xlsx";
                } else if (path.equals("consumable_asset")) {
                    moduleName = "易耗品导入模板.xlsx";
                } else if (path.equals("car_use")) {
                    moduleName = "车辆导入模板.xlsx";
                } else if (path.equals("enrol_student")) {
                    moduleName = "招生信息导入模版.xlsx";
                } else if (path.equals("teacher_power")) {
                    moduleName = "大数据师资力量导入模版.xlsx";
                } else if (path.equals("teacher_award")) {
                    moduleName = "教师获奖信息导入模版.xlsx";
                } else if (path.equals("salary")) {
                    moduleName = "工资单导入模版.xlsx";
                } else if (path.equals("admission")) {
                    moduleName = "录取信息导入模版.xlsx";
                } else if (path.equals("college_major_task")) {
                    moduleName = "院系专业计划导入模版.xlsx";
                } else if (path.equals("college_major_setting")) {
                    moduleName = "院系专业设置导入模版.xlsx";
                } else if (path.equals("new_student")) {
                    moduleName = "新生导入模版.xlsx";
                } else if (path.equals("stu_idcard")) {
                    moduleName = "身份账号姓名导入模版.xlsx";
                } else if (path.equals("stu_no_chsi_pic")) {
                    moduleName = "学生学籍照片导入模版.xlsx";
                } else if (path.equals("student_fee")) {
                    moduleName = "学生书杂费批量导入模板.xlsx";
                } else if (path.equals("student_loan")) {
                    moduleName = "学生助学贷款核销金额批量导入模板.xlsx";
                } else {
                    return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
                }
                log.debug("fileName=====" + file.getName());
//                response.setContentType("application/force-download");
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//                response.setContentType("image/**");
                response.setCharacterEncoding("UTF-8");
                // response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(moduleName, "UTF-8"));
                response.setHeader("file-type", "download");
                response.setHeader("file-name", URLEncoder.encode(moduleName, "utf-8"));
                response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
    }

    @Override
    public ResponseResult aliyunFileUpload(MultipartFile file) {
        String uploadPath = "https://xyht-sms.oss-cn-shanghai.aliyuncs.com/";
        String endpoint = "oss-cn-shanghai.aliyuncs.com";

        if (file.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        String fileName = file.getOriginalFilename();

        int size = Math.round(file.getSize() / 1024);
        int sizeMB = Math.round(size / 1024);
        if (sizeMB > fileSavePathConstant.getIMG_UPLOAD_MAX()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        }
        if (size == fileSavePathConstant.getFILE_UPLOAD_MIN()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_MIN);
        }
        log.debug(fileName + "-->" + size + "KB");

        String timeTemp = new Date().getTime() + "";

        String completePath = "";
        String newFileName = "";
        if (fileName.lastIndexOf(".") == -1) {
            completePath = uploadPath + timeTemp;
            newFileName = timeTemp;
        } else {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            completePath = uploadPath + timeTemp + "." + suffix;
            newFileName = timeTemp + "." + suffix;
        }

        OSS ossClient = new OSSClientBuilder().build(endpoint, fileSavePathConstant.getALIYUN_OSS_ACCESS_KEY_ID(), fileSavePathConstant.getALIYUN_OSS_ACCESS_KEY_SECRET());
        try {

            PutObjectRequest putObjectRequest = new PutObjectRequest("xyht-sms", newFileName, file.getInputStream());
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.debug("_____________++++++++" + result);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("oldFileName", fileName);
        map.put("newFileName", newFileName);
        map.put("path", completePath);
        return CommonResult.success(map);
    }

}
